<?php

class SJB_PromotionsManager extends SJB_ObjectManager
{
	public static function getAllPromotions()
	{
		$result = SJB_DB::query('SELECT `sid` FROM `promotions`');
		$promotions = array();
		foreach ($result as $promotion) 
			$promotions[] = self::getObjectBySID($promotion['sid']);
		
		return $promotions;
	}
	
	public static function getAllPromotionsInfo()
	{
		SJB_DB::query("UPDATE `promotions` SET `active` = 0 WHERE `active` = 1 AND `end_date` < NOW() - INTERVAL 1 DAY");
		$result = SJB_DB::query('SELECT `sid`, if(`end_date` < NOW() - INTERVAL 1 DAY, 2, `active`) as `active` FROM `promotions` ORDER BY `sid` DESC');
		$promotions = array();
		foreach ($result as $key => $promotion) {
			$promotions[$key] = SJB_ObjectDBManager::getObjectInfo('promotions', $promotion['sid']);
			$promotions[$key]['active'] = $promotion['active'];
		}
		
		return $promotions;
	}
	
	public static function savePromotionCode($promotionCode)
	{
		parent::saveObject('promotions', $promotionCode);
	}
	
	public static function getObjectBySID($sid)
	{
		$promotionCodeInfo = SJB_ObjectDBManager::getObjectInfo('promotions', $sid);
		
		if (!is_null($promotionCodeInfo)) {
			$promotionCode = new SJB_Promotions($promotionCodeInfo);
			$promotionCode->setSID($promotionCodeInfo['sid']);
			return $promotionCode;
		}
		return null;
	}
	
	public static function getCodeInfoBySID($sid)
	{
		$code_info = SJB_ObjectDBManager::getObjectInfo('promotions', $sid);
		return $code_info;
	}

	public static function deleteCodeBySID($sid)
	{
		parent::deleteObject('promotions', $sid);
	}
	
	public static function activateCodeBySID($sid)
	{
		return SJB_DB::query("UPDATE `promotions` SET `active` = 1 WHERE `sid` = ?n", $sid);
	}
	
	public static function deactivateCodeBySID($sid)
	{
		return SJB_DB::query("UPDATE `promotions` SET `active` = 0 WHERE `sid` = ?n", $sid);
	}
	
	public static function getCodeSIDByName($codeName)
	{
		$result = SJB_DB::queryValue("SELECT `sid` FROM `promotions` WHERE `code` = ?s LIMIT 1", $codeName);
		return $result ? $result['sid'] : false;
	}
	
	public static function getCodeInfoByName($codeName)
	{
		$result = SJB_DB::query("SELECT * FROM `promotions` WHERE `code` = ?s LIMIT 1", $codeName);
		$result = array_pop($result);
		return $result ? $result : array();
	}

	public static function checkCode($codeName, $productSIDs)
	{
		if (empty($codeName)) 
			return false;
			
		$where = " AND (`product_sid` = '' ";
		foreach ($productSIDs as $productSID) {
			$where .= " OR FIND_IN_SET({$productSID}, `product_sid`) ";
		}
		$where .= ")";
		$result = SJB_DB::query("SELECT * FROM `promotions` WHERE `active` = 1 AND (`start_date` IS NULL OR `start_date` <= NOW()) AND (`end_date`IS NULL OR `end_date` > NOW() - INTERVAL 1 DAY) AND `code` = ?s {$where}  LIMIT 1", $codeName);
		return $result?array_pop($result):false;
	}
	
	
	public static function addCodeToHistory($promotionCodes, $paymentSID = false, $userSID)
	{
		foreach ($promotionCodes as $promotionCode => $products) {
			$codeInfo = self::getCodeInfoBySID($promotionCode);
			$productsSIDs = implode(',', $products);
			SJB_DB::queryExec("INSERT INTO `promotions_history` (`user_sid`, `code_sid`, `payment_sid`, `product_sid`, `date`, `code_info`)
					VALUES (?n, ?n, ?n, ?s, NOW(), ?s)", $userSID, $promotionCode, $paymentSID, $productsSIDs, serialize($codeInfo));
		}		
	}

	public static function updatePaymentSID($codeHistorySID, $paymentSID)
	{
		SJB_DB::query("UPDATE `promotions_history` SET `payment_id` = ?n WHERE `id` = ?n", $paymentSID, $codeHistorySID);
	}
	
	public static function getAllHistory()
	{
		return SJB_DB::query("SELECT * FROM `promotions_history` ORDER BY code , `date` DESC");
	}

	public static function getCodeByPaymentSID($paymentSID)
	{
		$result = SJB_DB::query("SELECT `code` FROM `promotions_history` WHERE `payment_id` = ?n LIMIT 1", $paymentSID);
		return $result[0]['code'];
	}
	
	public static function getDiscountByID($id)
	{
		$info = self::getCodeInfoByName($id);
		return isset($info['discount'])?$info['discount']:1;
	}
	
	public static function issetActiveCodes()
	{
		$currentDate = date("Y-m-d");
		$result = SJB_DB::queryValue("SELECT count(*) FROM `promotions` WHERE `active`=1 AND `start_date` <= ?s AND `end_date` >= ?s", $currentDate);
		return $result > 0;
	}
	
	public static function  getUsesCodeBySID($sid)
	{
		$result = SJB_DB::queryValue("SELECT count(`sid`) FROM `promotions_history` WHERE `code_sid` = ?n", $sid);
		return $result ? $result : 0;
	}
}